<?php

namespace iBrand\Shop\Server\Controllers\V2;

use iBrand\Component\Order\Models\Order;
use iBrand\Component\Order\Repositories\OrderRepository;
use iBrand\Component\Payment\Models\Payment;
use iBrand\Shop\Core\Models\Balance;
use iBrand\Shop\Core\Models\BalanceOrder;
use iBrand\Shop\Core\Models\Refund;
use iBrand\Shop\Core\Repositories\CashRecordRepository;
use iBrand\Common\Controllers\Controller;
use iBrand\Shop\Core\Repositories\ClerkBalanceOrderRepository;

class StatisticsController extends Controller
{
    protected $orderRepository;
    protected $cashRecordRepository;
    protected $clerkBalanceOrderRepository;

    public function __construct(OrderRepository $orderRepository, CashRecordRepository $cashRecordRepository, ClerkBalanceOrderRepository $clerkBalanceOrderRepository)
    {
        $this->orderRepository = $orderRepository;
        $this->cashRecordRepository = $cashRecordRepository;
        $this->clerkBalanceOrderRepository = $clerkBalanceOrderRepository;
    }

    public function index()
    {
        $clerk = auth('clerk')->user();
        $shop_id = $clerk->shop_id;
        $time_start = date('Y-m-d') . ' 00:00:00';
        $time_end = date('Y-m-d') . ' 23:59:59';

        //总订单数
        $orders = $this->orderRepository->scopeQuery(function ($query) use ($time_start, $time_end, $shop_id) {
            return $query->where('status', Order::STATUS_PAY)->whereIn('type', [Order::TYPE_SHOP, Order::TYPE_SHOP_REFUND])->where('channel', 'shop')->where('channel_id', $shop_id)->where('created_at', '>=', $time_start)->where('created_at', '<=', $time_end);
        })->all();
        $total_order = $orders->count();

        //退换货
        $refunds = Refund::where('status', 1)->where('shop_id', $shop_id)->where('created_at', '>=', $time_start)->where('created_at', '<=', $time_end)->get();
        $refundAmount = $refunds->sum('actual_amount');
        $refundExchange = $refunds->where('type', 2)->count(); //换货
        $refundReturn = $refunds->where('type', 1)->count(); //退货


        //总销售额
        $total_amount = 0;
        $cash_pay_amount = 0;
        $pop_pay_amount = 0;
        $wx_pay_amount = 0;
        $ali_pay_amount = 0;
        $balance_pay_amount = 0;
        $refund_pay_amount = 0;
        if ($total_order > 0) {
            foreach ($orders as $order) {
                $payments = $order->payments()->where('status', Payment::STATUS_COMPLETED)->where('order_type', Order::class)->get();
                if ($payments->count() > 0) {
                    $total_amount += $payments->sum('amount');
                    $cash_pay_amount += $payments->where('channel', Payment::CHANNEL_CASH)->sum('amount');
                    $pop_pay_amount += $payments->where('channel', Payment::CHANNEL_POP_CASH_PAY)->sum('amount');
                    $wx_pay_amount += $payments->where('channel', Payment::CHANNEL_WX_PUB)->sum('amount');
                    $ali_pay_amount += $payments->where('channel', Payment::CHANNEL_ALI_SCAN_PAY)->sum('amount');
                    $balance_pay_amount += $payments->where('channel', Payment::CHANNEL_BALANCE)->sum('amount');
                    $refund_pay_amount += $payments->where('channel', Payment::CHANNEL_REFUND)->sum('amount');
                }
            }
        }

        $total_amount = $total_amount - $refund_pay_amount;

        $yesterday_start = date('Y-m-d', strtotime('-1 day')) . ' 00:00:00';
        $yesterday_end = date('Y-m-d', strtotime('-1 day')) . ' 23:59:59';
        $surplus_amount = 0;
        $ye_cash_records = $this->cashRecordRepository->getCashRecordPaginate(['created_at' => ['>=', $yesterday_start], 'shop_id' => $shop_id], ['created_at' => ['<=', $yesterday_end]], 0);
        if ($ye_cash_records->count() > 0) {
            $ye_income = $ye_cash_records->where('amount', '>', 0)->sum('amount');
            $ye_outcome = $ye_cash_records->where('amount', '<', 0)->sum('amount');
            $surplus_amount = $ye_income + $ye_outcome;
        }

        $today_cash_records = $this->cashRecordRepository->getCashRecordPaginate(['created_at' => ['>=', $time_start], 'shop_id' => $shop_id], ['created_at' => ['<=', $time_end]], 0);
        $income = 0;
        $outcome = 0;
        if ($today_cash_records->count() > 0) {
            $income = $today_cash_records->where('amount', '>', 0)->sum('amount');
            $outcome = $today_cash_records->where('amount', '<', 0)->sum('amount');
        }

        $count_balance_orders = 0;
        $total_balance_amount = 0;
        $balance_orders = $this->clerkBalanceOrderRepository->scopeQuery(function ($query) use ($time_start, $time_end, $shop_id) {
            return $query->where('shop_id', $shop_id)->where('created_at', '>=', $time_start)->where('created_at', '<=', $time_end)->whereHas('balanceOrder', function ($query) {
                return $query->where('pay_status', 1);
            });
        })->all();
        if ($balance_orders->count() > 0) {
            $count_balance_orders = $balance_orders->count();
            $balance_order_ids = $balance_orders->pluck('balance_order_id')->toArray();
            $total_balance_amount = Balance::where('type', Balance::TYPE_RECHARGE)->whereIn('origin_id', $balance_order_ids)->where('origin_type', BalanceOrder::class)->sum('value');
        }

        return $this->success([
            'total_order' => $total_order + $refunds->count(),
            'shop_total_order' => $total_order,
            'sales' => [
                'total_amount' => $total_amount,
                'cash_amount' => $cash_pay_amount,
                'pop_amount' => $pop_pay_amount,
                'wx_pay_amount' => $wx_pay_amount,
                'ali_pay_amount' => $ali_pay_amount,
                'balance_pay_amount' => $balance_pay_amount,
            ],
            'cash' => [
                'yesterday_surplus_amount' => $surplus_amount,
                'today_income' => $income,
                'today_outcome' => $outcome,
            ],
            'recharge' => [
                'count_balance_orders' => $count_balance_orders,
                'total_balance_amount' => $total_balance_amount,
            ],
            'refund' => [
                'refundAmount' => $refundAmount, //退款金额
                'refundExchange' => $refundExchange,//换货单据数
                'refundReturn' => $refundReturn //退货单据数
            ]
        ]);
    }
}